package game.leon.engine.net;

import game.leon.engine.net.codec.GateRawMessage;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

/**
 * User: bianpeng
 * Date: 11-12-27
 */
class GateIoHandler extends IoHandlerAdapter {
    private static final String SESSION = "SESSION";
    private Logger logger = Logger.getLogger(getClass());
    private GateMessageHandler gateMessageHandler;
    public GateIoHandler(GateMessageHandler gateMessageHandler) {
        this.gateMessageHandler = gateMessageHandler;
    }
    @Override
    public void sessionOpened(IoSession session) {
        logger.debug("client connected: " + session.getRemoteAddress());
        GateRawMessage rawMessage = new GateRawMessage(
                0, EngineConsts.SESSION_OPEN,
                new byte[]{0, 0, 0, 1});
        GateSession saved = new GateSession(session);
        session.setAttribute(SESSION, saved);
        gateMessageHandler.execute(saved, rawMessage);
    }
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        GateRawMessage rawMessage = (GateRawMessage) message;
        logger.debug("message received from user: " + rawMessage.getMessage());
        GateSession saved = (GateSession) session.getAttribute(SESSION);
        assert saved != null && saved.getIoSession() == session;
        gateMessageHandler.execute(saved, rawMessage);
    }
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        logger.debug("client disconnected: " + session.getRemoteAddress());
        GateRawMessage rawMessage = new GateRawMessage(
                0, EngineConsts.SESSION_OPEN,
                new byte[]{0, 0, 0, 1});
        GateSession saved = (GateSession) session.getAttribute(SESSION);
        assert saved != null && saved.getIoSession() == session;
        gateMessageHandler.execute(saved, rawMessage);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        logger.error("node connection errored");
        session.close(false);
    }
}
